package com.example.demo.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.nio.NioSctpServerChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.ReplayingDecoder;
import io.netty.util.CharsetUtil;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Description: TODO
 *
 * @author jihe.d
 * @date 2019/12/20 15:02
 */
public class Server {

    public static class IntDecoder extends ByteToMessageDecoder {

        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            out.add(in.readInt());
        }
    }

    public static class EchoServerHandler extends ChannelDuplexHandler {
        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            ctx.writeAndFlush(msg, promise);

        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {
            throwable.printStackTrace();
            ctx.close();
        }
    }
    public static void main(String[] args) throws InterruptedException {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //boss负责接收请求，分发给worker处理，worker负责处理请求
        NioEventLoopGroup boss = new NioEventLoopGroup(1, new NamedThreadFactory("netty-boss"));
        NioEventLoopGroup worker = new NioEventLoopGroup(5, new NamedThreadFactory("netty-worker"));
        serverBootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new IntDecoder());
                        ch.pipeline().addLast(new EchoServerHandler());
                    }
                });
        serverBootstrap.bind(8989).sync();
    }
}
